package org.jiamandan.com.strategy.listener;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jiamandan.com.config.UdpServerHandler;
import org.jiamandan.com.constant.BizConstant;
import org.jiamandan.com.constant.DXConstant;
import org.jiamandan.com.dto.DXBasicDto;
import org.jiamandan.com.entity.RechargePile;
import org.jiamandan.com.service.IRechargePileService;
import org.jiamandan.com.strategy.IDXContextListener;
import org.jiamandan.com.utils.CommonUtil;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;


@Service(value = DXConstant.Service.CMD_901)
@AllArgsConstructor
@Slf4j
public class DX901LoginListenerService implements IDXContextListener {


    private IRechargePileService iRechargePileService;


    @Override
    public void doExecute(DXBasicDto dto, Channel client) throws Exception {
        log.info("接收嘉满电-DX获取901设备登录指令(CMD=901)【"+dto.getDeviceNo()+"】报文:" + JSON.toJSONString(dto));
        try {
            reply(dto);
        }catch (Exception e){
            log.error("发送嘉满电-DX获取901设备登录指令(CMD=901)【"+dto.getDeviceNo()+"】报文失败："+e.getMessage());
        }
        //3AA3     00000001 8680650738780960
        //0100 36 00
        //32 00 00 01 05 05 06
        //0086806507387809 603836383 036353037333837383039363839383630383336313932344330363837303430
        String payload = dto.getData();
        String deviceVersion = convertHexString(StringUtils.substring(payload, 0, 8));
        String softwareVersion = convertHexString(StringUtils.substring(payload, 8, 16));
        //String imei = payload.substring(32, 62);
        String imei = CommonUtil.hexToString( payload.substring(32, 62)).trim();
        String ccId = CommonUtil.hexToString( payload.substring(62, 102)).trim();

        //TODO 存储登录信息
/*        LambdaQueryWrapper<PileActualData> queryWrapper =  Wrappers.<PileActualData>query().lambda().eq(PileActualData::getPileNo, dto.getDeviceNo());
        PileActualData pileActualData = Optional.ofNullable(iPileActualDataService.getOne(queryWrapper)).orElseGet(() -> PileActualData.builder().build());
        pileActualData.setUpdateTime(new Date());
        pileActualData.setDeviceVersion(softwareVersion);
        pileActualData.setModuleVersion("");
        pileActualData.setPileNo(dto.getDeviceNo());
        pileActualData.setSim(ccId);
        pileActualData.setImei(imei);
        iPileActualDataService.saveOrUpdate(pileActualData);    //更新信号处理
        //32 00 00 01  设备类型
        //05 05 06 00  软件版本
        //86 80 65 07 38 78 09 60  BCD编码
        //38 36 38 30 36 35 30 37 33 38 37 38 30 39 36  IMEI
        //38 39 38 36 30 38 33 36 31 39 32 34 43 30 36 38 37 30 34 30  CCID
        //client.writeAndFlush(DXConstant.Cmd.CMD_901+"01");
        //更新版本
        RechargePile rechargePile = iRechargePileService.getByPileNo(dto.getDeviceNo());
        rechargePile.setDeviceVersion(softwareVersion);
        rechargePile.setUpdateTime(new Date());
        rechargePile.setLiveStatus(BizConstant.OnOffLine.ONLINE);
        iRechargePileService.updateById(rechargePile);*/
    }

    private void reply(DXBasicDto dto){
        UdpServerHandler.sendMessage("00",dto,"00",DXConstant.Cmd.CMD_901);
    }

    private static String convertHexString(String hexString) {
        if (hexString.length() % 2 != 0) {
            throw new IllegalArgumentException("输入的十六进制字符串长度必须是2的倍数。");
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < hexString.length(); i += 2) {
            String part = hexString.substring(i, i + 2);
            // 解析为整数，处理无符号数值
            String value = StringUtils.leftPad(String.valueOf(Integer.parseUnsignedInt(part, 16)),2, "0");
            stringBuilder.append(value);
        }
        return stringBuilder.toString();
    }
}
